package com.hk.photo;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hk.action.Action;
import com.hk.action.ActionForward;
import com.hk.dtos.PhotoDto;
import com.hk.dtos.UserDto;
import com.hk.file.FileManager;
import com.hk.service.LoginService;
import com.hk.service.PhotoService;
import com.jungbo.file.dto.FileDto;

public class PhotoWritegoAction implements Action {
	public ActionForward execute(HttpServletRequest request,
			HttpServletResponse response) {
		ActionForward forword=new ActionForward();
	
		
		
	PhotoService manager=PhotoService.getInstance();
	FileManager fmanager=new FileManager();
	
	PhotoDto dto = new PhotoDto();
	FileDto fdto = new FileDto();
	LoginService lmanager = LoginService.getInstance();
	String id = request.getParameter("id");
    String tcontent = request.getParameter("content");
    String title = request.getParameter("title");
    String tfcount = request.getParameter("fcount");
      
    
    
    int fcount=0;
    if(tfcount!=null || tfcount!="0"){
    fcount = Integer.parseInt(tfcount);
    }
    if(fcount==0){
    	
    	
    	request.setAttribute("emsg", "Please upload photo");
		request.setAttribute("eurl", "photocontrol?command=plist");
    	forword.setUrl("error");
    	forword.setRedirect(false);

    	return forword;
//    	
//		location.href("control.jsp?command=start");
    }
 
    
    String bcontent = tcontent.replace("\n", "<br>");
    String content = bcontent.replace(" ", "&nbsp;");
    
    

    
    int fseq=0;
    ArrayList<PhotoDto> result = manager.maxSeq();
    
	int seq=0;
	
	for(int i=0; i<result.size(); i++){
		PhotoDto s =result.get(i);
	    
	    if(seq<s.getSeq())
	    	seq=s.getSeq();
		}
	ArrayList<FileDto> fresult = fmanager.maxfseq();
	
	for(int i=0; i<fresult.size(); i++){
    FileDto fs =fresult.get(i);
    
    if(fseq<fs.getFileseq())
    	fseq=fs.getFileseq();
	}
	
	seq = seq + 1;
    dto.setId(id);
    dto.setContent(content);
    dto.setTitle(title);
    
    manager.insPhoto(dto);
    
    if(tfcount!=null){
    for(int i=0; i<fcount; i++){
    fdto.setSeq(seq);
    fdto.setFileseq(fseq-i);
    fmanager.fseqUpdate(fdto);
    }
    }
    fmanager.addmod();
//    fmanager.pmodbid();
	lmanager.pointup(id);
	 UserDto t = new UserDto();
	    
	    t=lmanager.login(id);
	    if(t.getScore()%10==0){
	    	lmanager.autup(id);	
	    }
	    
	forword.setUrl("pstart");
	forword.setRedirect(false);

	return forword;
}//
	
	
}
